<?php
// 本地路径转web路径
if(!function_exists('l2w')){
    function l2w($path){
        $strSearch  = $_SERVER["DOCUMENT_ROOT"];
        $strReplace = rtrim(SITE_PATH, "/");
        return str_replace($strSearch, $strReplace, $path);
    }
}

if(!function_exists('w2l')){
    function w2l($path){
        $strSearch  = rtrim(SITE_PATH, "/");
        $strReplace = $_SERVER["DOCUMENT_ROOT"];
        return str_replace($strSearch, $strReplace, $path);
        return "";
    }
}


// 绝对路径转相对路径
if(!function_exists('a2r')){
    function a2r($path){
        if(IS_CLI){
            $strSearch = DOCUMENT_ROOT;
        }else {
            $strSearch = $_SERVER["DOCUMENT_ROOT"];
        }
        return str_replace($strSearch, "", $path);
    }
}

// 相对路径转绝对路径
if(!function_exists('r2a')){
    function r2a($path){
        if(IS_CLI){
            $strSearch = DOCUMENT_ROOT;
        }else {
            $strSearch = $_SERVER["DOCUMENT_ROOT"];
        }
        return $strSearch . str_replace($strSearch, "", $path);
    }
}

function is_phone($string){
    $check = '/^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$/';
    return preg_match($check, $string);
}


//获取指定位数随机数
function GetRandStr($len){
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i=0; $i<$len; $i++)
    {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}



//根据地址返回 省市区
function handleAddress($address =''){
    preg_match('/(.*?(省|自治区|北京市|天津市))/', $address, $matches);
    if(count($matches) > 1){
        $province = $matches[count($matches) - 2];
        $address = str_replace($province, '', $address);
    }
    preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
    if(count($matches) > 1){
        $city = $matches[count($matches) - 2];
        $address = str_replace($city, '', $address);
    }
    preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
    if(count($matches)>1){
        $area = $matches[count($matches) - 2];
        $address = str_replace($area, '', $address);
    }
    return [
        'province' => isset($province) ? $province : '',
        'city' => isset($city) ? $city : '',
        'area' => isset($area) ? $area : '',
    ];
}



function cover2UTF8($string){
    $encode = mb_detect_encoding($string);
    if($encode != 'UTF-8'){
        $string = mb_convert_encoding($string, 'utf8', $encode);
    }
    return $string;
}



/**
 * @param $ip
 * @return string
 * 通过ip获取地址
 */
function getIpAddress($ip){
    if (empty($ip) || !isset($ip)){
        return '';
    }
    $host = "http://iploc.market.alicloudapi.com";
    $path = "/v3/ip";
    $method = "GET";
    $appcode = "e6bdec1ee15c497fafb30cf817ba72bf";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "ip=".$ip;
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $data = curl_exec($curl);
    $start = strpos($data,'{');
    $end   = strpos($data,'}');
    $address = substr($data,$start,$end);
    $address = json_decode($address,true);
    if ($address['status'] == 1){
        return $address['province'].' '.$address['city'];
    }else{
        return '';
    }
}


/**
 * 半角转全角
 * @param string $str
 * @return string
 **/
function dbc2Sbc($str){
    return preg_replace_callback(
    // 半角字符
        '/[\x{0020}\x{0020}-\x{7e}]/',
        // 编码转换
        // 0x0020是空格，特殊处理，其他半角字符编码+0xfee0即可以转为全角
        '($unicode=char2Unicode(\'\0\')) == 0x0020 ? unicode2Char（0x3000） : (($code=$unicode+0xfee0) > 256 ? unicode2Char($code) : chr($code))',
        $str
    );
}

/**
 * 全角转半角
 * @param string $str
 * @return string
 **/
function sbc2Dbc($str){
    return preg_replace(
    // 全角字符
        '/[\x{3000}\x{ff01}-\x{ff5f}]/ue',
        // 编码转换
        // 0x3000是空格，特殊处理，其他全角字符编码-0xfee0即可以转为半角
        '($unicode=char2Unicode(\'\0\')) == 0x3000 ? " " : (($code=$unicode-0xfee0) > 256 ? unicode2Char($code) : chr($code))',
        $str
    );
}

/**
 * [checkDateIsValid 校验日期格式是否正确]
 * @param  [type] $date    [日期]
 * @param  array  $formats [需要检验的格式数组]
 * @return [boolean]
 */
function checkDateIsValid($dates) {
    $unixTime = strtotime($dates);
    $formats = array("Y-m-d", "Y/m/d", "Ymd");
    if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
        return false;
    }
    //校验日期的有效性，只要满足其中一个格式就OK
    foreach ($formats as $format) {
        $strtotime = date($format, $unixTime);
        if ($strtotime == $dates) {
            return true;
        }
    }

    return false;
}


/**
 * 更具字符串汉字首字母获取大写字母
 */
function getFirstCharter($str){
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z'))
        return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'GBK', $str);
    $s2 = iconv('GBK', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284)return 'A';
    if ($asc >= -20283 && $asc <= -19776)return 'B';
    if ($asc >= -19775 && $asc <= -19219)return 'C';
    if ($asc >= -19218 && $asc <= -18711)return 'D';
    if ($asc >= -18710 && $asc <= -18527)return 'E';
    if ($asc >= -18526 && $asc <= -18240)return 'F';
    if ($asc >= -18239 && $asc <= -17923)return 'G';
    if ($asc >= -17922 && $asc <= -17418)return 'H';
    if ($asc >= -17417 && $asc <= -16475)return 'J';
    if ($asc >= -16474 && $asc <= -16213)return 'K';
    if ($asc >= -16212 && $asc <= -15641)return 'L';
    if ($asc >= -15640 && $asc <= -15166)return 'M';
    if ($asc >= -15165 && $asc <= -14923)return 'N';
    if ($asc >= -14922 && $asc <= -14915)return 'O';
    if ($asc >= -14914 && $asc <= -14631)return 'P';
    if ($asc >= -14630 && $asc <= -14150)return 'Q';
    if ($asc >= -14149 && $asc <= -14091)return 'R';
    if ($asc >= -14090 && $asc <= -13319)return 'S';
    if ($asc >= -13318 && $asc <= -12839)return 'T';
    if ($asc >= -12838 && $asc <= -12557)return 'W';
    if ($asc >= -12556 && $asc <= -11848)return 'X';
    if ($asc >= -11847 && $asc <= -11056)return 'Y';
    if ($asc >= -11055 && $asc <= -10247)return 'Z';
    return null;
}